//
//  PYMyPyqListViewController.swift
//  SheYangBigData
//
//  Created by 宋海胜 on 2021/1/7.
//  Copyright © 2021 叁拾叁. All rights reserved.
//

import UIKit
import MJRefresh
import RxSwift
import RxDataSources
import Then
import SDCycleScrollView

class PYMyPyqListViewController: SYBaseTableViewController, UITableViewDelegate {
    
    let headView = PYHeaderView()
    fileprivate var vm: PYMyListViewModel!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.automaticallyAdjustsScrollViewInsets = false
        
        setRightNavItem()
        setTableView()
        setNoDataView()
        
        setupViewModel()
        self.title = "我的农友圈"
    }
    
    fileprivate func setupViewModel() {
        vm = PYMyListViewModel()
        vm.tableView = tableView
        vm.emptyViewParams = ("", "", 40.0, 30.0)
        tableView.vg_pageProtocol = vm
        vm.getList(type: .myList(page: self.vm.vg_pageNo, size:self.vm.size), dispose: dispose)
        vm.getDataClosure = {[weak self] page in
            if let `self` = self {
                self.vm.getList(type: .myList(page: self.vm.vg_pageNo, size:self.vm.size), dispose: self.dispose)
            }
        }
        vm.loadDataClosure = {[weak self] success in
            if let `self` = self {
                if success {
                    self.loadDataSuccessed()
                    self.headView.myListConfigure(self.vm.model)
                }
            }
        }
    }
    
    func loadDataSuccessed() {
        
        DispatchQueue.main.async {
            self.setDataSource()
        }
    }
    
    func setRightNavItem() {
        let item: UIBarButtonItem = UIBarButtonItem(title: "发布", style: UIBarButtonItem.Style.plain, target: self, action: #selector(rightAction))
        self.navigationItem.rightBarButtonItem=item
    }
    
    func setTableView() {
        
        //创建表格视图
        self.tableView = UITableView(frame: CGRect(x: 0, y: NAV_HEIGHT, width: SCREEN_WIDTH, height: SCREEN_HEIGHT-NAV_HEIGHT - BOTTOM_SAFE_HEIGHT), style:.grouped)
        //        self.tableView.rowHeight = 100
        //        self.tableView.rowHeight = UITableView.automaticDimension
        self.tableView.separatorStyle = .none
        self.tableView.delegate = self
        //创建一个重用的单元格
        self.tableView!.register(UITableViewCell.self, forCellReuseIdentifier: "Cell")
        self.view.addSubview(self.tableView!)
        
        
        tableView.rx.itemSelected
            .subscribe(onNext:{ [weak self] indexPath in
                if let `self` = self {
                    let sectionDatas: [NSVoListModel] = self.vm.dataSource[indexPath.section].voList ?? []
                    
                    let vc = PYMySinglePyqDetailViewController(id: (sectionDatas[indexPath.row].id ?? "0"))
                    vc.backClosure = {[weak self] _ in
                        if let `self` = self {
                            self.vm.getList(type: .myList(page: self.vm.vg_pageNo, size:self.vm.size), dispose: self.dispose)
                        }
                        
                    }
                    self.navigationController?.pushViewController(vc, animated: true)
                    
                }
            })
            .disposed(by:dispose)
    }
    
    func setNoDataView() {
        noDataView = SYNoDataView(frame: CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: SCREEN_HEIGHT-NAV_HEIGHT - 200.0.autoWidth()))
        noDataView.isHidden = true
        tableView.addSubview(noDataView)
    }
    
    func setDataSource() {
        //初始化数据
        var listSections: [PYQMyListSection] = []
        self.vm.dataSource.forEach { (value) in
            let section = PYQMyListSection(header: value.time ?? "", items: value.voList ?? [])
            listSections.append(section)
        }
        
        let sections = Observable.just(listSections)
        
        //创建数据源
        let dataSource = RxTableViewSectionedAnimatedDataSource<PYQMyListSection>(
            //设置单元格
            configureCell: { ds, tv, ip, item in
                
                var videoImgUrls: [String] = []
                var isVideo = false
                item.resourceList?.forEach({ (value) in
                    if let u = value.videoImgUrl {
                        isVideo = true
                        videoImgUrls.append(String(format: "%@%@", IMGIP, u))
                    } else if let l = value.fileFullPath {
                        videoImgUrls.append(String(format: "%@%@", IMGIP, l))
                    }
                })
                print("第一个cell\(ip.row)，共\(videoImgUrls.count)张image")
                
                if videoImgUrls.count != 0 {
                    
                    let cell: PYQListImageCell = tv.dequeueReusableCell(withIdentifier: "Cell")
                        as? PYQListImageCell ?? PYQListImageCell(style: .default, reuseIdentifier: "Cell")
                    
                    cell.selectionStyle = .none
                    cell.configure(urls: videoImgUrls, model: item, isVideo: isVideo)
                    
                    return cell
                } else {
                    let cell: PYQListCell = tv.dequeueReusableCell(withIdentifier: "Cell")
                        as? PYQListCell ?? PYQListCell(style: .default, reuseIdentifier: "Cell")
                    cell.configure( model: item)
                    cell.selectionStyle = .none
                    return cell
                }
                
                
            },
            //设置分区头标题
            titleForHeaderInSection: { ds, index in
                return ds.sectionModels[index].header
            })
        tableView.dataSource = nil
        //绑定单元格数据
        sections
            .bind(to: tableView.rx.items(dataSource: dataSource))
            .disposed(by: dispose)
        
    }
    
    @objc func rightAction() {
        let vc = PYEditViewController()
        vc.backClosure = {[weak self] _ in
            if let `self` = self {
                self.vm.getList(type: .myList(page: self.vm.vg_pageNo, size:self.vm.size), dispose: self.dispose)
            }
            
        }
        self.vg_present(vc, animated: true)
    }
    
    func tableView(_ tableVdiew: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        if section == 0 {
            
            headView.tipBgView.isHidden = true
            headView.headBt.isHidden = true
            headView.frame = CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: 290.0.autoWidth())
            return headView;
        } else {
            let view = PYQYearCell()
            view.frame = CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: 65.0.autoWidth())
            self.vm.dataSource.forEach { (value) in
                view.yearLb.text = value.time
            }
            return view
        }
    }
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        if section == 0 {
            return 280.0.autoWidth()
        } else {
            return 65.0.autoWidth()
        }
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        return nil
    }
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0.1
    }
}

extension PYMyPyqListViewController: SDCycleScrollViewDelegate {
    
    func cycleScrollView(_ cycleScrollView: SDCycleScrollView!, didSelectItemAt index: Int) {
        print("选择了轮播图\(index)")
    }
}


//自定义Section
struct PYQMyListSection {
    var header: String
    var items: [Item]
}

extension PYQMyListSection : AnimatableSectionModelType {
    typealias Item = NSVoListModel
    
    var identity: String {
        return header
    }
    
    init(original: PYQMyListSection, items: [Item]) {
        self = original
        self.items = items
    }
}

extension NSVoListModel: IdentifiableType {
    var identity: String {
        return uuid!
    }
    
    typealias Identity = String
}
